// NewTrainingFramework.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "glModel.h"
#include "Shaders.h"
#include <conio.h>
#include "glObject.h"
#include "SceneManager.h"
#include "Camera.h"
#include "glLighting.h"
#include <math.h>


SceneManager *s_manager;
CCamera *camera;
glLighting *light;
float uv_offset;
float p_angleX,n_angleX,p_angleY,n_angleY;
float angle_sLight;

int Init ( ESContext *esContext )
{
	angle_sLight=0;
	light=glLighting::GetInstance();
	p_angleX=-0.05f;
	n_angleX=0.05f;
	p_angleY=-0.05f;
	n_angleY=0.05f;
	camera=CCamera::GetInstance();
	s_manager=new SceneManager;
	s_manager->initScene();
	
	return 0;
}

void Draw ( ESContext *esContext )
{
	glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
	glClear(GL_COLOR_BUFFER_BIT);
	s_manager->s_Draw();
	eglSwapBuffers ( esContext->eglDisplay, esContext->eglSurface );
}

void Update ( ESContext *esContext, float deltaTime )
{
	if(angle_sLight>=6.29)
		angle_sLight=0;
	else
		angle_sLight+=deltaTime;
	light->Light.spotDirection.x=1000.0f*cos(angle_sLight);
	light->Light.spotDirection.z=1000.0f*sin(angle_sLight);
	uv_offset = uv_offset + deltaTime;
	if(uv_offset>=1.0f)
		uv_offset=0;
}

void Key ( ESContext *esContext, unsigned char key, bool bIsPressed)
{
	switch(key){
		case 87:
			//cout<<"w"<<endl
			camera->MoveForward();
			s_manager->update();
			break;
		case 83:
			//cout<<"s"<<endl;
			camera->MoveBack();
			s_manager->update();
			break;
		case 65:
			//cout<<"a"<<endl;
			camera->MoveLeft();
			s_manager->update();
			break;
		case 68:
			//cout<<"d"<<endl;
			camera->MoveRight();
			s_manager->update();
			break;
		case 69:
			//cout<<"d"<<endl;
			camera->MoveDown();
			s_manager->update();
			break;
		case 81:
			//cout<<"d"<<endl;
			camera->MoveUp();
			s_manager->update();
			break;

		case 37:
			//cout<<"left"<<endl;
			camera->RotateY(p_angleY);
			s_manager->update();
			break;
		case 39:
			//cout<<"right"<<endl;
			camera->RotateY(n_angleY);
			s_manager->update();
			break;
		case 38:
			//cout<<"up"<<endl;
			camera->RotateX(n_angleX);
			s_manager->update();
			break;
		case 40:
			//cout<<"down"<<endl;
			camera->RotateX(p_angleX);
			s_manager->update();
			break;
	}
}

void CleanUp()
{
	s_manager->CleanUp();
	delete s_manager;
	CCamera::DetroyInstance();
}

int _tmain(int argc, _TCHAR* argv[])
{
	ESContext esContext;

    esInitContext ( &esContext );

	esCreateWindow ( &esContext, "Hello Triangle", 960, 720, ES_WINDOW_RGB);

	if ( Init ( &esContext ) != 0 )
		return 0;

	esRegisterDrawFunc ( &esContext, Draw );
	esRegisterUpdateFunc ( &esContext, Update );
	esRegisterKeyFunc ( &esContext, Key);

	esMainLoop ( &esContext );

	//releasing OpenGL resources
	CleanUp();

	//identifying memory leaks
	MemoryDump();
	printf("Press any key...\n");
	_getch();

	return 0;
}

